﻿// ===============================================================================
// XCI.NET 西安交通信息WinForm开发框架 2018 版权所有
// ===============================================================================
using System;
using System.Collections.Generic;

namespace XCI.Extensions
{
    /// <summary>
    /// Dictionary扩展操作
    /// </summary>
    public static class DictionaryExtensions
    {
        /// <summary>
        /// 获取指定键对应值,如果不存在指定键,返回指定的默认值.
        /// </summary>
        /// <param name="dic">字典对象</param>
        /// <param name="key">键对象</param>
        public static string GetString<TKey, TValue>(this IDictionary<TKey, TValue> dic, TKey key)
        {
            if (dic.TryGetValue(key, out var result))
            {
                return result.ToStringOrEmpty();
            }
            return string.Empty;
        }

        /// <summary>
        /// 获取指定键对应值,如果不存在指定键,返回指定的默认值.
        /// </summary>
        /// <param name="dic">字典对象</param>
        /// <param name="key">键对象</param>
        /// <param name="defaultValueFunc">默认值</param>
        public static TValue Get<TKey, TValue>(this IDictionary<TKey, TValue> dic, TKey key, Func<TValue> defaultValueFunc = null)
        {
            if (!dic.TryGetValue(key, out var result) && defaultValueFunc != null)
            {
                result = defaultValueFunc.Invoke();
            }
            return result;
        }

        /// <summary>
        /// 设置键值
        /// </summary>
        /// <param name="dic">字典对象</param>
        /// <param name="key">键对象</param>
        /// <param name="value">值对象</param>
        public static IDictionary<TKey, TValue> Set<TKey, TValue>(this IDictionary<TKey, TValue> dic, TKey key, TValue value)
        {
            dic[key] = value;
            return dic;
        }

        /// <summary>
        /// 获取指定键对应值,如果不存在指定键,添加指定的键和值.
        /// </summary>
        /// <param name="dic">字典对象</param>
        /// <param name="key">键对象</param>
        /// <param name="value">值对象</param>
        public static TValue GetOrSet<TKey, TValue>(this IDictionary<TKey, TValue> dic, TKey key, TValue value)
        {
            if (!dic.ContainsKey(key))
            {
                dic.Add(key, value);
                return value;
            }
            return dic[key];
        }
    }
}